package servlets;

import java.io.IOException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sessions.HelpManagerRemote;
import sessions.UserManagerRemote;
import entities.User;
import exceptions.HelpRequestException;

/**
 * Servlet implementation class AskHelp
 */
public class AskHelp extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AskHelp() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String from = request.getParameter("from");
		String to = request.getParameter("to");
		String message = request.getParameter("message");
		try {
			Hashtable<String, String> env = new Hashtable<String, String>();
			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"org.jnp.interfaces.NamingContextFactory");
			env.put(Context.PROVIDER_URL, "localhost:1099");
			InitialContext jndiContext = new InitialContext(env);
			Object ref = null;
			ref = jndiContext.lookup("UserManager/remote");
			UserManagerRemote ur = (UserManagerRemote) ref;
			User fromUser = ur.fetch(from);
			User toUser = ur.fetch(to);
			ref = jndiContext.lookup("HelpManager/remote");
			HelpManagerRemote hr = (HelpManagerRemote) ref;
			try {
				hr.request(fromUser, toUser, message);
				response.sendRedirect("./HelpReqs");
				return;
			} catch (HelpRequestException e) {
				String error = "<font face='tahoma' size='2'>Richiesta errata - Impossibile inoltrare la richiesta.</font><br></font>";
				HttpSession session = request.getSession();
				session.setAttribute("error", error);
				response.sendRedirect("error.jsp");
				return;
			}
		} catch (NamingException e) {
			e.printStackTrace();
		}
		
	}

}
